package com.jinglin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.jinglin.entity.dto.UserMessageCountDto;
import com.jinglin.entity.dto.UserMessageExtendDto;
import com.jinglin.entity.enums.MessageReadTypeEnum;
import com.jinglin.entity.enums.MessageTypeEnum;
import com.jinglin.entity.po.*;
import com.jinglin.entity.query.SimplePage;
import com.jinglin.entity.query.UserMessageQuery;
import com.jinglin.entity.vo.PaginationResultVO;
import com.jinglin.exception.BusinessException;
import com.jinglin.mapper.UserMessageMapper;
import com.jinglin.service.UserMessageService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jinglin.service.VideoCommentService;
import com.jinglin.service.VideoInfoPostService;
import com.jinglin.service.VideoInfoService;
import com.jinglin.utils.JsonUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 用户消息表 服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2025-04-06
 */
@Service
public class UserMessageServiceImpl extends ServiceImpl<UserMessageMapper, UserMessage> implements UserMessageService {
    @Autowired
    private VideoInfoService videoInfoService;
    @Autowired
    private VideoCommentService videoCommentService;
    @Autowired
    private VideoInfoPostService videoInfoPostService;
    @Autowired
    private UserMessageMapper userMessageMapper;
    @Override
    public void saveUserMessage(String videoId, String sendUserId, MessageTypeEnum messageTypeEnum, String content, String replyCommentId) {
        VideoInfo videoInfo = videoInfoService.getById(videoId);
        if (videoId == null) {
            return;
        }
        // 这个dto专门用来对应userMessage表中的extend_json字段
        UserMessageExtendDto extendDto = new UserMessageExtendDto();
        extendDto.setMessageContent(content);

        //由于收藏，点赞可以点击取消点击取消的特殊性，所以我们只记录第一次操作的消息  已经记录过消息，不再记录
        if (ArrayUtils.contains(new Integer[]{MessageTypeEnum.LIKE.getType(), MessageTypeEnum.COLLECTION.getType()}, messageTypeEnum)) {
            LambdaQueryWrapper<UserMessage> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(UserMessage::getSendUserId, sendUserId);
            wrapper.eq(UserMessage::getVideoId, videoId);
            wrapper.eq(UserMessage::getMessageType, messageTypeEnum.getType());
            int count = this.count(wrapper);
            if (count > 0){
                return;
            }
        }
        String userId = null;

        UserMessage userMessage = new UserMessage();
        userMessage.setSendUserId(sendUserId);
        userMessage.setVideoId(videoId);
        userMessage.setMessageType(messageTypeEnum.getType());
        userMessage.setReadType(MessageReadTypeEnum.NO_READ.getType());
        userMessage.setCreateTime(LocalDateTime.now());



        //评论处理
        if (replyCommentId != null){
            // 证明有接收人。这个接收人不一定是视频发布者
            VideoComment commentInfo = videoCommentService.getById(replyCommentId);
            if (commentInfo.getUserId().equals(commentInfo.getReplyUserId())){
                // 自己给自己回复的评论，不需要记录消息
                return;
            }
            if (commentInfo != null){
                // 我给别人发消息，别人要接受到信息，而不是视频所有者接受消息
                userId = commentInfo.getUserId();
                // 设置被回复的这条评论的内容
                extendDto.setMessageContentReply(commentInfo.getContent());
            }
        } else {
            // 如果为null，那么说明这条评论是顶级评论
            //如果是作者自己发的评论，那么不需要消息提示
            if (videoInfo.getUserId().equals(sendUserId)){
                return;
            }
        }


        // 系统消息特殊处理,消息的发送者是系统管理员
        if (MessageTypeEnum.SYS == messageTypeEnum){
            // 目前涉及系统管理员的操作就只有审核
            VideoInfoPost videoInfoPost = videoInfoPostService.getById(videoId);
            extendDto.setAuditStatus(videoInfoPost.getStatus());
        }

        // 这个userId代表着这条消息是属于哪个用户的。应该哪个用户收到这个消息
        userMessage.setUserId(userId);
        userMessage.setExtendJson(JsonUtils.convertObj2Json(extendDto));
        this.save(userMessage);
    }

    @Override
    public PaginationResultVO loadMessage(Integer messageType, String userId, Integer pageNo) {
        int count = userMessageMapper.count(userId);
        Integer pageSize = 15;

        SimplePage page = new SimplePage(pageNo, count, pageSize);
        List<UserMessage> list = userMessageMapper.loadMessage(page.getStart(), pageSize, userId,messageType);
        for (UserMessage userMessage : list) {
            String extendJson = userMessage.getExtendJson();
            UserMessageExtendDto userMessageExtendDto = JsonUtils.convertJson2Obj(extendJson, UserMessageExtendDto.class);
            userMessage.setExtendDto(userMessageExtendDto);
        }
        PaginationResultVO<UserMessage> result = new PaginationResultVO(count, page.getPageSize(), page.getPageNo(), page.getPageTotal(), list);

        return result;


    }

    @Override
    public Integer countGroup(String userId,Integer readType) {
       return userMessageMapper.countGroup(userId,readType);

    }

    @Override
    public List<UserMessageCountDto> getMessageTypeNoReadCount(String userId) {

        return userMessageMapper.getMessageTypeNoReadCount(userId);


    }

    @Override
    public void readAll(Integer messageType, String userId) {
        LambdaUpdateWrapper<UserMessage> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(UserMessage::getUserId,userId);
        wrapper.set(UserMessage::getReadType,MessageReadTypeEnum.READ.getType());
        this.update(wrapper);
    }
}
